#include "head.h"

int sendFile(int net_fd){


    char *file_name = "1b.txt";
    
    // 打开文件
    int file_fd = open(file_name, O_RDWR);
    
    // 获得文件信息
    struct stat st;
    memset(&st, 0, sizeof(st));
    fstat(file_fd, &st);
    
    //printf("file_size: %ld \n", st.st_size);
    off_t file_size = st.st_size;
    send(net_fd, &file_size, sizeof(off_t), MSG_NOSIGNAL);
    
    
    // 写给客户端文件名字
    int name_len = strlen(file_name);
    send(net_fd, &name_len, sizeof(int), MSG_NOSIGNAL);
    send(net_fd, file_name, name_len, MSG_NOSIGNAL);

    // 循环读取文件内容, 循环发送
    while(1){
        // 读取文件内容
        char buf[1024] = {0};
        ssize_t file_len = read(file_fd, buf, sizeof(buf));
        if(file_len == 0){
            printf("文件读完 \n");
            break;
        }

        int ret = send(net_fd, &file_len, sizeof(ssize_t), MSG_NOSIGNAL);
        if(ret == -1){
            printf("对方断开链接 \n");
            break;
        }
        // 文件内容: 发送给客户端
        ret = send(net_fd, buf, file_len, MSG_NOSIGNAL);
        if(ret == -1){
            printf("对方断开链接 \n");
            break;
        }
    }

    return 0;
}

